import {useState,useRef,useEffect} from 'react';
function useDrag(){
    let [position,setPosition] = useState({x:0,y:0});
    const moveElement = useRef(null);
    useEffect(()=>{
        const start = (event)=>{
            //获取触摸目标在视口中的X坐标和Y坐标
            const {clientX,clientY} = event;
            //记录一下初始的X和Y坐标
            const startX = clientX;
            const startY = clientY;
            const move = (event)=>{
                const {clientX,clientY} = event;
                const newPositionX = position.x+(clientX-startX);
                const newPositionY = position.y+(clientY-startY);
                setPosition({x:newPositionX,y:newPositionY});
            }
            const end = ()=>{
                moveElement.current.removeEventListener('mousemove',move);
                moveElement.current.removeEventListener('mouseup',end);
            }
            moveElement.current.addEventListener('mousemove',move);
            moveElement.current.addEventListener('mouseup',end);
        }
        //给要移动的元素添加一个事件监听touchstart,对应的方法是start
        moveElement.current.addEventListener('mousedown',start);
        //当组件卸载时执行此销毁函数,移除事件监听
        return ()=>{
            moveElement.current.removeEventListener('mousedown',start);
        }
    },[position]);
    return [position,moveElement];
}
export default useDrag;